import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import type {
  facilityTypeEnum,
  operationStatusEnum
} from '~/store/assetManagement/facilityManagement/typings'
import type { workAreaEnum } from '~/store/assetManagement/assetAreaManage/typings'
import type {
  PowerDistributionFacilitiesDataItemType,
  PowerDistributionFacilitiesStateType
} from './typings'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { useStore } from 'vuex'
// import dayjs from 'dayjs'
import {
  ElCard,
  ElSpace,
  ElLink,
  ElButton,
  ElIcon,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElDatePicker,
  ElMessageBox,
  ElMessage
} from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import AliIcon from '~/components/AliIocn'
import ProSaasTable from '~/components/ProSaasTable'
import PowerDistributionFacilitiesOptions from './options'
import ColorfulBadge from '~/components/ColorfulBadge'
import ExportExcel from '~/components/ExportExcel'
import ImportModal from '../../components/powerDistributionFacilitiesComponents/ImportModal'
import useVuexGetters from '~/hooks/useVuexGetters'
import { EL_SPACE_SIZE_SECOND_GEAR } from '~/utils/const'
import { handleTrim } from '~/utils/util'
import styles from '../../index.module.scss'
import { useRouter } from 'vue-router'

export default defineComponent(function PowerDistributionFacilities() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const router = useRouter()
  const formValues = reactive<PowerDistributionFacilitiesDataItemType>({})
  const state = reactive<PowerDistributionFacilitiesStateType>({
    exportVisible: false,
    modalVisible: false,
    importVisible: false,
    type: 'read',
    record: {}
  })
  const userState = useVuexGetters('user', ['permission'])
  const powerDistributionFacilitiesState = useVuexGetters('powerDistributionFacilities', [
    'tenantDictDictionaryOpt',
    'operationStatusSelectList',
    'operationStatusEnum'
  ])
  const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList'])
  // 所属街道
  const streetManagementState = useVuexGetters('streetManagement', ['streetSelectList'])

  // 打开导出弹框
  const handleChangeExportModal = () => {
    state.exportVisible = !state.exportVisible
  }

  // 切换type类型
  // const handleChangeOptionsType = (type: PowerDistributionFacilitiesStateType['type']) => {
  //   state.type = type
  // }

  // 打开操作弹框
  const handleChangeOptionsModal = (
    type: PowerDistributionFacilitiesStateType['type'],
    record?: PowerDistributionFacilitiesDataItemType,
    visible?: boolean
  ) => {
    state.modalVisible = visible || !state.modalVisible
    state.record = record || {}
    state.type = type
    if (!state.modalVisible) proSaasTableRef.value!?.toSearch()
  }

  // 切换导入弹框
  const handleChangeImprotModal = () => {
    state.importVisible = !state.importVisible
    if (!state.importVisible) proSaasTableRef.value!?.toSearch()
  }

  // 执行删除操作
  const handleDeleteSelectedData = async (params: string) => {
    await store
      .dispatch('powerDistributionFacilities/DeletePowerDistributionFacilitiesInfo', {
        ids: params
      })
      .then((res) => {
        if (res?.code === 200) {
          proSaasTableRef.value!?.clearSelection?.()
          proSaasTableRef.value!?.toSearch()
          ElMessage({ type: 'success', message: '操作成功' })
        }
      })
  }

  // 打开删除消息确认框
  const handleOpenDeleteConfirm = (record?: PowerDistributionFacilitiesDataItemType) => {
    if (!record && !proSaasTableRef.value!.selecteds?.length) {
      ElMessage({ type: 'warning', message: '请选择要删除的数据' })
      return
    }
    const params =
      record?.id || proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {record?.id && <p class="delete-title">确认删除数据?</p>}
          {!record?.id && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认删除选中数据？'}
            </p>
          )}
          <p class="delete-content">删除后不可恢复，是否确认删除。</p>
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      cancelButtonClass: 'el-button--primary is-plain',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    })
      .then(async () => {
        // !record?.id
        //   ? `确认删除选中的${proSaasTableRef.value!.selecteds?.length}条数据`
        //   : '确定将选择数据删除?',

        await store
          .dispatch('powerDistributionFacilities/CheckDeletedPowerDistributionFacilitiesInfo', {
            ids: params
          })
          .then(async (result) => {
            if (!result.success) return
            if (result?.data?.canDel === 0 && result?.data?.msg) {
              ElMessageBox({
                title: '确认提示',
                message: result?.data?.msg,
                showCancelButton: true,
                confirmButtonText: '确认',
                cancelButtonText: '取消',
                closeOnClickModal: false, // 点遮罩层不关弹窗
                draggable: true // 可拖拽
              })
                .then(() => {
                  handleDeleteSelectedData(params)
                })
                .catch(() => {
                  proSaasTableRef.value!?.clearSelection?.()
                  proSaasTableRef.value!?.toSearch()
                })
            } else {
              handleDeleteSelectedData(params)
            }
          })
      })
      .catch(() => {})
  }

  //  所属街道
  const remoteMethod = (query: string) => {
    if (query) {
      store.dispatch('streetManagement/GetStreetSelectListByUser', { key: query })
    }
  }

  // 按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }

  // 清空搜索
  const clearSearchTable = async () => {
    if (formValues.categoryId === '') {
      delete formValues.categoryId // 设施类型
    }
    if (formValues.workAreaName === '') {
      delete formValues.workAreaName // 所属区域
    }
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  onMounted(() => {
    // 获取设备类别下拉列表
    store.dispatch('powerDistributionFacilities/TenantDictDictionaryGet')
    // 获取投运状态下拉列表
    store.dispatch('powerDistributionFacilities/GetOperationStatusSelectList')
    // 获取所属区域下拉列表
    store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser')

    // 从道路管理跳转带入道路名称查询
    const row: PowerDistributionFacilitiesDataItemType = router.currentRoute.value.query
    if (row.id) {
      formValues.streetId?.push(row?.id as string)
      const value = streetManagementState.streetSelectList.value.filter(
        (item: workAreaEnum) => item.id === row.id
      )
      if (value.length === 0) {
        streetManagementState.streetSelectList.value.push({
          name: row.name,
          id: row.id
        })
      }
      setTimeout(() => {
        proSaasTableRef.value!?.toSearch()
      }, 500)
    }
  })

  const columns: TableColumnProps<PowerDistributionFacilitiesDataItemType>[] = [
    {
      label: '设施名称',
      prop: 'name',
      minWidth: 180,
      fixed: 'left',
      unFixed: true,
      disabled: true,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '设施类型',
      prop: 'categoryName',
      minWidth: 180,
      sortable: true,
      disabled: true
    },
    {
      label: '所属10kV线路',
      prop: 'tenKv',
      minWidth: 180,
      sortable: true,
      hidden: true
    },
    {
      label: '高压杆号',
      prop: 'highNo',
      minWidth: 180,
      sortable: true,
      hidden: true
    },
    {
      label: '空开容量',
      prop: 'capacity',
      minWidth: 180,
      sortable: true,
      hidden: true
    },
    {
      label: '所属区域',
      prop: 'workAreaName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '所属街道',
      prop: 'streetName',
      minWidth: 180,
      sortable: true,
      showOverflowTooltip: true
    },
    {
      label: '投运状态',
      prop: 'isDeliver',
      minWidth: 180,
      enumValues: powerDistributionFacilitiesState.operationStatusEnum,
      sortable: true,
      render: (option, value) => (
        <ColorfulBadge
          value={value}
          enumKey={option.row.isDeliver as number}
          options={{ success: 1, info: 2, warning: 0 }}
        />
      )
    },
    {
      label: '投运日期',
      prop: 'deliverDate',
      minWidth: 180,
      sortable: true
    },
    {
      label: '更新时间',
      prop: 'updateTime',
      minWidth: 220,
      sortable: true
    },
    {
      label: '备注',
      prop: 'memo',
      minWidth: 180,
      sortable: true,
      hidden: true,
      showOverflowTooltip: true
    },
    {
      label: '操作',
      prop: 'options',
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      minWidth: 280,
      render: ({ row }) => (
        <ElSpace size={EL_SPACE_SIZE_SECOND_GEAR}>
          {userState.permission.value.has('assets_distribution_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('read', row)}>
              <AliIcon type="icon-chakan" />
              &nbsp; 详情
            </ElLink>
          )}
          {userState.permission.value.has('assets_distribution_update') && (
            <ElLink type="primary" onClick={() => handleChangeOptionsModal('update', row)}>
              <AliIcon type="icon-bianji" />
              &nbsp; 编辑
            </ElLink>
          )}
          {userState.permission.value.has('assets_distribution_remove') && (
            <ElLink type="primary" onClick={() => handleOpenDeleteConfirm(row)}>
              <AliIcon type="icon-shanchu" />
              &nbsp; 删除
            </ElLink>
          )}
        </ElSpace>
      )
    }
  ]
  return () => {
    // 日期变时 搜索
    const props = {
      onChange: () => {
        setTimeout(() => {
          proSaasTableRef.value!?.toSearch()
        }, 100)
      }
    }

    return state.modalVisible ? (
      <PowerDistributionFacilitiesOptions
        record={state.record}
        type={state.type}
        changeType={handleChangeOptionsModal}
        cancel={() => handleChangeOptionsModal('read')}
      />
    ) : (
      <ElCard shadow="never" class="covered-with-content">
        <ProSaasTable<PowerDistributionFacilitiesDataItemType>
          tableId="powerDistributionFacilities"
          ref={proSaasTableRef}
          columns={columns}
          rowKey="id"
          hasSelection
          dispatchType="powerDistributionFacilities/GetPowerDistributionFacilitiesList"
          headerTitle={
            <>
              {userState.permission.value.has('assets_distribution_add') && (
                <ElButton type="primary" onClick={() => handleChangeOptionsModal('add')}>
                  <ElIcon>
                    <Plus />
                  </ElIcon>
                  &nbsp; 新增
                </ElButton>
              )}
              {userState.permission.value.has('assets_distribution_remove') && (
                <ElButton type="danger" onClick={() => handleOpenDeleteConfirm()}>
                  <AliIcon type="icon-shanchu" />
                  &nbsp; 删除
                </ElButton>
              )}
              {/* {userState.permission.value.has('assets_distribution_import') && ( */}
              <ElButton type="primary" onClick={() => handleChangeImprotModal()}>
                <AliIcon type="icon-daoru" />
                &nbsp; 导入
              </ElButton>
              {/* )} */}
              {userState.permission.value.has('assets_distribution_export') && (
                <ElButton type="primary" onClick={() => handleChangeExportModal()}>
                  <AliIcon type="icon-daochu" />
                  &nbsp; 导出
                </ElButton>
              )}
            </>
          }
          searchParams={{
            name: formValues.name && handleTrim(formValues.name),
            deliverDate: undefined,
            deliverBeginTime: formValues.deliverDate?.[0],
            deliverEndTime: formValues.deliverDate?.[1]
          }}
          searchFormProps={{
            model: formValues
          }}
          searchformResponsiveCol={[
            <ElFormItem
              key="name"
              prop="name"
              // label="设施名称"
            >
              <ElInput
                v-model={formValues.name}
                {...{ maxlength: 20 }}
                placeholder="设施名称"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem
              key="categoryId"
              prop="categoryId"
              // label="设施类型"
            >
              <ElSelect
                v-model={formValues.categoryId}
                placeholder="设施类型"
                clearable
                onChange={() => {
                  proSaasTableRef.value!?.toSearch()
                }}
                onClear={clearSearchTable}
              >
                {powerDistributionFacilitiesState.tenantDictDictionaryOpt?.value?.map(
                  (item: facilityTypeEnum) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )
                )}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem
              key="isDeliver"
              prop="isDeliver"
              // label="投运状态"
            >
              <ElSelect
                v-model={formValues.isDeliver}
                placeholder="投运状态"
                clearable
                onChange={() => {
                  proSaasTableRef.value!?.toSearch()
                }}
              >
                {powerDistributionFacilitiesState.operationStatusSelectList?.value?.map(
                  (item: operationStatusEnum) => (
                    <ElOption key={item?.dictKey} label={item?.dictValue} value={item?.dictKey!} />
                  )
                )}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem
              key="workAreaName"
              prop="workAreaName"
              // label="所属区域"
            >
              <ElSelect
                v-model={formValues.workAreaName}
                placeholder="所属区域"
                filterable
                clearable
                onChange={() => {
                  proSaasTableRef.value!?.toSearch()
                }}
                onClear={clearSearchTable}
              >
                {assetWorkAreaState.workAreaSelectList?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.name!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="streetId" prop="streetId" label="">
              <ElSelect
                v-model={formValues.streetId}
                clearable
                filterable
                remote
                multiple
                reserve-keyword
                remote-method={remoteMethod}
                onChange={clearSearchTable}
                placeholder="所属街道"
              >
                {streetManagementState.streetSelectList?.value?.map((item: workAreaEnum) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem
              key="deliverDate"
              prop="deliverDate"
              // label="投运日期"
            >
              <ElDatePicker
                v-model={formValues.deliverDate}
                start-placeholder="开始投运日期"
                end-placeholder="结束投运日期"
                valueFormat="YYYY-MM-DD"
                format="YYYY-MM-DD"
                type="daterange"
                {...props}
              />
            </ElFormItem>
          ]}
        />
        {state.exportVisible && (
          <ExportExcel
            visible={state.exportVisible}
            dispatchType="powerDistributionFacilities/ExportPowerDistributionFacilitiesInfo"
            columns={proSaasTableRef.value?.filterColumns}
            payload={{ params: formValues }}
            onCancel={handleChangeExportModal}
          />
        )}
        {state.importVisible && <ImportModal doCancel={handleChangeImprotModal} />}
      </ElCard>
    )
  }
})
